package com.zszedu.service;

import com.zszedu.mapper.UserMapper;
import com.zszedu.pojo.User;
import com.zszedu.utils.MD5Util;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;


@DubboService
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    //注册用户
    @Override
    public Boolean addUser(String phone, String pwd) {
        //判断手机号是以注册过
        if (userMapper.queryPhone(phone) != null) {
            throw new RuntimeException("手机号以被注册");
        }
        //手动为对象赋值
        User user = new User();
        user.setPhone(phone);//手机号
        user.setLoginPassword(pwd);//将密码加密
        user.setAddTime(new Date());//用户注册时间
        user.setLastLoginTime(new Date());//用户最近登录时间

        return userMapper.addUser(user) > 0;
    }

    //根据手机号查询用户
    @Override
    public User queryPhone(String phone) {
        return userMapper.queryPhone(phone);
    }


    //查询所有用户数量,并且存储在Redis中
    @Override
    public Integer queryCount() {
        return userMapper.queryCount();
    }

    //根据手机号密码查询用户
    @Override
    public User queryUser(String phone, String pwd) {
        User user = userMapper.queryUser(phone, pwd);
        //数据为空则，用户输入错误
        if (user == null) {
            throw new RuntimeException("账号或密码错误");
        }
        return user;
    }

    //根据手机号和验证码修改密码
    @Override
    public Boolean editUser(String phone, String pwd) {
        //手动为对象赋值
        User user = new User();
        user.setPhone(phone);//手机号
        user.setLoginPassword(MD5Util.getMD5(pwd));//将密码加密
        user.setLastLoginTime(new Date());//用户最近登录时间

        return userMapper.editUser(user) > 0;
    }

    //根据手机号修改姓名身份证（如果身份证被使用了，则抛出异常）
    @Override
    public Boolean editUserReal(String name, String card, String phone) {
        User user = new User();
        user.setName(name);
        user.setIdCard(card);
        user.setPhone(phone);

        //返回T则，该身份证已经被实名认证过了
        if (queryCard(user.getIdCard()) != null) {
            throw new RuntimeException("身份证已被使用！");

        //判断身份证属性是否为空，不为空则说明该账号已经实名认证了
        } else if (userMapper.queryPhone(phone).getIdCard() != null && !userMapper.queryPhone(phone).getIdCard().equals("")) {
            throw new RuntimeException("已实名认证过，请勿进行重复操作");
        }

        //修改的行数不是 1 则说明失败
        return userMapper.editUserReal(user) > 0;
    }

    //使用身份证号码查询用户信息
    @Override
    public User queryCard(String idCard) {
        return userMapper.queryCard(idCard);
    }

    //根据ID查询用户信息
    @Override
    public User queryById(Long id) {
        return userMapper.queryById(id);
    }

    @Override
    public Boolean editHeaderImage(Integer id, String headerImage) {
        return userMapper.editHeaderImage(id,headerImage) > 0;
    }

    //根据id修改上次登录时间
    @Override
    public void editTime(Long id) {
        userMapper.editTime(id,new Date());
    }
}
